// import React, { useRef, useEffect } from 'react';
// import BScroll, { Options } from '@better-scroll/core';
// import Pullup from '@better-scroll/pull-up';
// import PullDown from '@better-scroll/pull-down';
// import ScrollBar from '@better-scroll/scroll-bar';
// import ObserveDOM from '@better-scroll/observe-dom'
// import NestedScroll from '@better-scroll/nested-scroll'
// import { Spinning } from '@/design';
// import styles from './Scroll.less';

// BScroll.use(ScrollBar);
// BScroll.use(ObserveDOM as any);
// BScroll.use(NestedScroll as any)

// interface IScroll {
//   config?: Options
//   onPullingDown?: (...arg: any) => Promise<any>
//   onPullingUp?: (...arg: any) => Promise<any>
//   onScroll?: (pos: Position) => void
//   hasMore?: boolean
//   hasHeader?: boolean
//   hasFooter?: boolean
//   hideFooter?: boolean
// }

// export interface Position {
//   x: number;
//   y: number;
// };

// const defaultConfig = {
//   scrollbar: {
//     fade: true,
//   },
//   observeDOM: true,
//   scrollY: true,
//   click: true,
//   dblclick: true,
//   eventPassthrough: 'horizontal',
//   nestedScroll: true,
//   pullDownRefresh: true
//   // preventDefaultException:{className:/(^|\s)swiper(\s|$)/}
// };

// export const Scroll: React.FC<IScroll> = props => {
//   const scrollRef = useRef<BScroll>();
//   const wrapRef = useRef<HTMLDivElement>(null);

//   /* 初始化滾動 */
//   const initScroll = () => {
//     const { config, onPullingDown, onPullingUp, onScroll } = props;
//     const newConfig: any = { ...defaultConfig, ...config };
//     // console.log(newConfig);
//     onPullingUp && (newConfig['pullUpLoad'] = true);
//     const { pullDownRefresh, pullUpLoad } = newConfig;
//     pullUpLoad && BScroll.use(Pullup);
//     pullDownRefresh && BScroll.use(PullDown);
//     // console.log("🚀 ~ file: Scroll.tsx ~ line 56 ~ initScroll ~ newConfig", newConfig)
//     let bs = new BScroll(wrapRef.current as HTMLDivElement, newConfig);

//     // 下拉刷新
//     pullDownRefresh &&
//       bs.on('pullingDown', () => {
//         onPullingDown
//           ? onPullingDown().finally(() => {
//             bs.finishPullDown();
//             bs.refresh();
//           })
//           : window.history.go(0);
//       });

//     // 上拉加載
//     pullUpLoad &&
//       bs.on('pullingUp', () => {
//         onPullingUp &&
//           onPullingUp().finally(() => {
//             bs.finishPullUp();
//             bs.refresh();
//           });
//       });

//     // 滾動監聽
//     onScroll && bs.on('scroll', (pos: Position) => {
//       onScroll(pos)
//     })

//     scrollRef.current = bs;
//   };

//   useEffect(() => {
//     // console.log(props.refresh)
//     setTimeout(() => {
//       initScroll();
//     }, 0);
//     return () => {
//       scrollRef.current && scrollRef.current.destroy()
//     };
//   }, []);

//   return (
//     <div
//       ref={wrapRef}
//       className={`${styles.wrapper} ${props.hasFooter ? styles.hasFooter : ''}`}
//     >
//       <div className={styles.content}>
//         {props.hasHeader && <div className={styles.hasHeader}></div>}
//         <div className={styles.pull_down}>
//           <Spinning type="colors" size={16} />
//           鬆開刷新
//         </div>
//         <div className={styles.main}>{props.children}</div>
//         <div className={styles.pull_Up}>
//           {props.hasMore ? (
//             <>
//               <Spinning state="dark" type="circle" size={28} />
//               <span className={styles.tips}>加載中…</span>
//             </>
//           ) : <span>- 沒有更多了 -</span>}
//         </div>
//       </div>
//     </div>
//   );
// };


import React, { useRef, useEffect } from 'react';
import BScroll, { Options } from '@better-scroll/core';
import Pullup from '@better-scroll/pull-up';
import PullDown from '@better-scroll/pull-down';
import ScrollBar from '@better-scroll/scroll-bar';
import ObserveDOM from '@better-scroll/observe-dom'
import NestedScroll from '@better-scroll/nested-scroll'
import { Spinning } from '@/design';
import styles from './Scroll.less';

BScroll.use(ScrollBar);
BScroll.use(ObserveDOM as any);
BScroll.use(NestedScroll as any)

interface IScroll {
  refresh?: number
  config?: Options
  /** 下拉刷新 */
  onPullingDown?: () => void
  /** 上拉加載 */
  onPullingUp?: () => void
  /** 滾動事件 */
  onScroll?: (pos: Position) => void
  hasMore?: boolean
  hasHeader?: boolean
  hasFooter?: boolean
  hideFooter?: boolean
}

export interface Position {
  x: number;
  y: number;
};

const defaultConfig = {
  scrollbar: {
    fade: true,
  },
  observeDOM: true,
  scrollY: true,
  // click: true,
  // dbclick: true,
  // HWCompositing: false,
  eventPassthrough: 'horizontal',
  nestedScroll: true,
  pullDownRefresh: true,
  stopPropagation: true,
  preventDefaultException: {
    className: /(^|\s)touch(\s|$)/
  }
};

export const Scroll: React.FC<IScroll> = props => {
  const scrollRef = useRef<BScroll>();
  const wrapRef = useRef<HTMLDivElement>(null);

  /* 初始化滾動 */
  const initScroll = () => {
    const { config, onPullingDown, onPullingUp, onScroll } = props;
    const newConfig: any = { ...defaultConfig, ...config };
    // console.log(newConfig);
    onPullingUp && (newConfig['pullUpLoad'] = true);
    const { pullDownRefresh, pullUpLoad } = newConfig;
    pullUpLoad && BScroll.use(Pullup);
    pullDownRefresh && BScroll.use(PullDown);
    // console.log("🚀 ~ file: Scroll.tsx ~ line 56 ~ initScroll ~ newConfig", newConfig)
    let bs = new BScroll(wrapRef.current as HTMLDivElement, newConfig);

    // 下拉刷新
    pullDownRefresh &&
      bs.on('pullingDown', () => {
        onPullingDown ? onPullingDown() : window.history.go(0);
      });

    // 上拉加載
    pullUpLoad &&
      bs.on('pullingUp', () => {
        onPullingUp && onPullingUp()
      });

    // 滾動監聽
    onScroll && bs.on('scroll', (pos: Position) => {
      onScroll(pos)
    })

    scrollRef.current = bs;
  };

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.finishPullDown();
      scrollRef.current.finishPullUp();
      scrollRef.current.refresh();
    }
  }, [props.refresh])

  useEffect(() => {
    // console.log(props.refresh)
    setTimeout(() => {
      initScroll();
    }, 0);
    return () => {
      scrollRef.current && scrollRef.current.destroy()
    };
  }, []);

  return (
    <div
      ref={wrapRef}
      className={`${styles.wrapper} ${props.hasFooter ? styles.hasFooter : ''}`}
    >
      <div className={`content ${styles.content}`}>
        {props.hasHeader && <div className={styles.hasHeader}></div>}
        <div className={styles.pull_down}>
          <Spinning type="colors" size={16} />
          鬆開刷新
        </div>
        <div className={styles.main}>{props.children}</div>
        {!props.hideFooter && <div className={styles.pull_Up}>
          {props.hasMore ? (
            <>
              <Spinning state="dark" type="circle" size={28} />
              <span className={styles.tips}>加載中…</span>
            </>
          ) : <span>- 沒有更多了 -</span>}
        </div>}
      </div>
    </div>
  );
};